<!-- MarkerList完整示例 -->
<!doctype html>
<html lang="zh-CN">

<head>
    <!-- 原始地址：//webapi.amap.com/ui/1.0/ui/misc/MarkerList/examples/index.html -->
    <base href="//webapi.amap.com/ui/1.0/ui/misc/MarkerList/examples/" />
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
    <title>完整示例</title>
    <link rel="stylesheet" type="text/css" href="./index.css">
</head>

<body>
    <div id="outer-box">
        <div id="container" tabindex="0"></div>
        <div id="panel" class="scrollbar1">
            <ul id="myList">
            </ul>
        </div>
        <ul id="btnList">
            <li>
                <input value="美食数据" type="button" data-path="//a.amap.com/amap-ui/static/data/restaurant.json" />
            </li>
            <li>
                <input value="酒店数据" type="button" data-path="//a.amap.com/amap-ui/static/data/hotel.json" />
            </li>
            <li>
                <input value="选中第一个" type="button" data-enable='markerList.getData().length>0' data-eval='markerList.selectByDataIndex(0)' />
            </li>
            <li>
                <input value="选中最后一个" type="button" data-enable='markerList.getData().length>0' data-eval='markerList.selectByDataReverseIndex(0)' />
            </li>
            <li>
                <input value="清除选中" type="button" data-enable='!!markerList.getSelectedDataId()' data-eval='markerList.clearSelected()' />
            </li>
            <li>
                <input value="清除数据" type="button" data-enable='markerList.getData().length>0' data-eval='markerList.clearData()' />
            </li>
        </ul>
    </div>
    <script type="text/javascript" src='//webapi.amap.com/maps?v=1.4.3&key=02a37b38c4b33a671f1cd1584b54adc8></script>
    <!-- UI组件库 1.0 -->
    <script src="//webapi.amap.com/ui/1.0/main.js?v=1.0.11"></script>
    <script type="text/javascript">
    //创建地图
    var map = new AMap.Map('container', {
        zoom: 9
    });

    AMapUI.loadUI(['misc/MarkerList', 'overlay/SimpleMarker', 'overlay/SimpleInfoWindow'],
        function(MarkerList, SimpleMarker, SimpleInfoWindow) {

            //即jQuery/Zepto
            var $ = MarkerList.utils.$;

            var defaultIconStyle = 'red', //默认的图标样式
                hoverIconStyle = 'green', //鼠标hover时的样式
                selectedIconStyle = 'purple' //选中时的图标样式
            ;

            var markerList = new MarkerList({
                map: map,
                //ListElement对应的父节点或者ID
                listContainer: "myList", //document.getElementById("myList"),
                //选中后显示

                //从数据中读取位置, 返回lngLat
                getPosition: function(item) {
                    return [item.longitude, item.latitude];
                },
                //数据ID，如果不提供，默认使用数组索引，即index
                getDataId: function(item, index) {

                    return item.id;
                },
                getInfoWindow: function(data, context, recycledInfoWindow) {

                    if (recycledInfoWindow) {

                        recycledInfoWindow.setInfoTitle(data.name);
                        recycledInfoWindow.setInfoBody(data.address);

                        return recycledInfoWindow;
                    }

                    return new SimpleInfoWindow({
                        infoTitle: data.name,
                        infoBody: data.address,
                        offset: new AMap.Pixel(0, -37)
                    });
                },
                //构造marker用的options对象, content和title支持模板，也可以是函数，返回marker实例，或者返回options对象
                getMarker: function(data, context, recycledMarker) {

                    var label = String.fromCharCode('A'.charCodeAt(0) + context.index);

                    if (recycledMarker) {
                        recycledMarker.setIconLabel(label);
                        return;
                    }

                    return new SimpleMarker({
                        containerClassNames: 'my-marker',
                        iconStyle: defaultIconStyle,
                        iconLabel: label
                    });
                },
                //构造列表元素，与getMarker类似，可以是函数，返回一个dom元素，或者模板 html string
                getListElement: function(data, context, recycledListElement) {

                    var label = String.fromCharCode('A'.charCodeAt(0) + context.index);

                    //使用模板创建
                    var innerHTML = MarkerList.utils.template('<div class="poi-imgbox">' +
                        '    <span class="poi-img" style="background-image:url(<%- data.pic %>)"></span>' +
                        '</div>' +
                        '<div class="poi-info-left">' +
                        '    <h3 class="poi-title">' +
                        '        <%- label %>. <%- data.name %>' +
                        '    </h3>' +
                        '    <div class="poi-info">' +
                        '        <span class="poi-price">' +
                        '            <%= data.price %>' +
                        '        </span>' +
                        '        <p class="poi-addr"><%- data.address %></p>' +
                        '    </div>' +
                        '</div>' +
                        '<div class="clear"></div>', {
                            data: data,
                            label: label
                        });

                    if (recycledListElement) {
                        recycledListElement.innerHTML = innerHTML;
                        return recycledListElement;
                    }

                    return '<li class="poibox">' +
                        innerHTML +
                        '</li>';
                },
                //列表节点上监听的事件
                listElementEvents: ['click', 'mouseenter', 'mouseleave'],
                //marker上监听的事件
                markerEvents: ['click', 'mouseover', 'mouseout'],
                //makeSelectedEvents:false,
                selectedClassNames: 'selected',
                autoSetFitView: true
            });

            window.markerList = markerList;

            markerList.on('selectedChanged', function(event, info) {

                checkBtnStats();

                if (info.selected) {

                    console.log(info);

                    if (info.selected.marker) {
                        //更新为选中样式
                        info.selected.marker.setIconStyle(selectedIconStyle);
                    }

                    //选中并非由列表节点上的事件触发，将关联的列表节点移动到视野内
                    if (!info.sourceEventInfo.isListElementEvent) {

                        if (info.selected.listElement) {
                            scrollListElementIntoView($(info.selected.listElement));
                        }
                    }
                }

                if (info.unSelected && info.unSelected.marker) {
                    //更新为默认样式
                    info.unSelected.marker.setIconStyle(defaultIconStyle);
                }
            });

            markerList.on('listElementMouseenter markerMouseover', function(event, record) {

                if (record && record.marker) {

                    forcusMarker(record.marker);

                    //this.openInfoWindowOnRecord(record);

                    //非选中的id
                    if (!this.isSelectedDataId(record.id)) {
                        //设置为hover样式
                        record.marker.setIconStyle(hoverIconStyle);
                        //this.closeInfoWindow();
                    }
                }
            });

            markerList.on('listElementMouseleave markerMouseout', function(event, record) {

                if (record && record.marker) {

                    if (!this.isSelectedDataId(record.id)) {
                        //恢复默认样式
                        record.marker.setIconStyle(defaultIconStyle);
                    }
                }
            });

            //数据输出完成
            markerList.on('renderComplete', function(event, records) {

                checkBtnStats();
            });

            // markerList.on('*', function(type, event, res) {
            //     console.log(type, event, res);
            // });

            //加载数据
            function loadData(src, callback) {

                $.getJSON(src, function(data) {

                    markerList._dataSrc = src;

                    //渲染数据
                    markerList.render(data);

                    if (callback) {
                        callback(null, data);
                    }
                });
            }

            var $btns = $('#btnList input[data-path]');

            /**
             * 检测各个button的状态
             */
            function checkBtnStats() {
                $('#btnList input[data-enable]').each(function() {

                    var $input = $(this),
                        codeEval = $input.attr('data-enable');

                    $input.prop({
                        disabled: !eval(codeEval)
                    });
                });
            }

            $('#btnList').on('click', 'input', function() {

                var $input = $(this),
                    dataPath = $input.attr('data-path'),
                    codeEval = $input.attr('data-eval');

                if (dataPath) {
                    loadData(dataPath);
                } else if (codeEval) {
                    eval(codeEval);
                }

                checkBtnStats();
            });

            loadData($btns.attr('data-path'));

            function forcusMarker(marker) {
                marker.setTop(true);

                //不在地图视野内
                if (!(map.getBounds().contains(marker.getPosition()))) {

                    //移动到中心
                    map.setCenter(marker.getPosition());
                }
            }

            function isElementInViewport(el) {
                var rect = el.getBoundingClientRect();

                return (
                    rect.top >= 0 &&
                    rect.left >= 0 &&
                    rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                    rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                );
            }

            function scrollListElementIntoView($listEle) {

                if (!isElementInViewport($listEle.get(0))) {
                    $('#panel').scrollTop($listEle.offset().top - $listEle.parent().offset().top);
                }

                //闪动一下
                $listEle
                    .one('webkitAnimationEnd oanimationend msAnimationEnd animationend',
                        function(e) {
                            $(this).removeClass('flash animated');
                        }).addClass('flash animated');
            }


        });
    </script>
</body>

</html>